<template>
  <div class="p-2" @click="menuHide">
    <el-row :gutter="24">
      <!-- 树 -->
      <el-col :lg="5" :xs="24">
        <el-card shadow="hover">
          <el-input v-model="queryParams.name" placeholder="输入树节点名称搜索" clearable>
            <template #append>
              <el-button type="primary" icon="Search" @click="handleQuery" />
            </template>
          </el-input>
          <el-tree
            class="mt-2"
            ref="deptTreeRef"
            node-key="id"
            :data="buildingTreeList"
            :props="{ label: 'name', children: 'children' }"
            :expand-on-click-node="false"
            :default-expanded-keys="defaultExpandKeys"
            :filter-node-method="filterNode"
            highlight-current
            @node-contextmenu.prevent="openContextMenu"
            @node-click="handleNodeClick"
          />
        </el-card>
      </el-col>
      <el-col :lg="19" :xs="24">
        <div style="background: #fff; padding: 10px 20px">
          <el-tabs v-model="activeName" class="ss-tabs" @tab-click="handleTabClick">
            <el-tab-pane label="宿舍信息" :name="1">
              <building-list ref="buildingList" :source-id="currentNodeData.sourceId" v-show="listType=='T'"></building-list>
              <floor-list ref="floorList" :source-id="currentNodeData.sourceId" v-show="listType=='B'"></floor-list>
              <room-list ref="roomList" :source-id="currentNodeData.sourceId" v-show="listType=='F'"></room-list>
              <member-list ref="memberList" :node-id="currentNodeData.id" :source-id="currentNodeData.sourceId" v-show="listType=='R'"></member-list>
            </el-tab-pane>
            <el-tab-pane label="学生信息" :name="2">
              <member-list-all ref="memberListAll" :node-id="currentNodeData.id" :source-id="currentNodeData.sourceId"></member-list-all>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-col>
    </el-row>
    <div v-show="showMenu" class="custom-menu" v-hasPermi="['dormitory:buildingTree:setting']">
      <ul>
        <li @click="menuItemAdd" v-show="currentNodeData.type!='R'">新增{{ addText }}</li>
        <li @click="menuItemUpdate" v-show="currentNodeData.type!='T'">修改</li>
        <li @click="menuItemDelete" v-show="currentNodeData.type!='T'">删除</li>
        <li @click="menuHide">取消</li>
      </ul>
    </div>
    <building-dialog ref="buildingDialog" :node-id="currentNodeData.id" @onSuccess="reloadDatas"></building-dialog>
    <floor-dialog ref="floorDialog" :node-id="currentNodeData.id" :building-id="currentNodeData.sourceId" @onSuccess="reloadDatas"></floor-dialog>
    <room-dialog ref="roomDialog" :node-id="currentNodeData.id" :floor-id="currentNodeData.sourceId" @onSuccess="reloadDatas"></room-dialog>
  </div>
</template>

<script setup name="BuildingTree" lang="ts">
import { listBuildingTree, getBuildingTree, delBuildingTree, addBuildingTree, updateBuildingTree } from '@/api/dormitory/buildingTree';
import { BuildingTreeVO, BuildingTreeQuery, BuildingTreeForm } from '@/api/dormitory/buildingTree/types';
import BuildingDialog from './modules/BuildingDialog.vue';
import BuildingList from './modules/BuildingList.vue';
import FloorDialog from './modules/FloorDialog.vue';
import FloorList from './modules/FloorList.vue';
import RoomDialog from './modules/RoomDialog.vue';
import RoomList from './modules/RoomList.vue';
import MemberList from './modules/MemberList.vue';
import MemberListAll from './modules/MemberListAll.vue';

type BuildingTreeOption = {
  id: number;
  name: string;
  children?: BuildingTreeOption[];
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const buildingTreeList = ref<BuildingTreeVO[]>([]);
const buildingTreeOptions = ref<BuildingTreeOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);
const showMenu = ref(false);
const buildingDialog = ref<InstanceType<typeof BuildingDialog>>();
const floorDialog = ref<InstanceType<typeof FloorDialog>>();
const roomDialog = ref<InstanceType<typeof RoomDialog>>();
const buildingList = ref<InstanceType<typeof BuildingList>>();
const floorList = ref<InstanceType<typeof FloorList>>();
const roomList = ref<InstanceType<typeof RoomList>>();
const memberList = ref<InstanceType<typeof MemberList>>();
const memberListAll = ref<InstanceType<typeof MemberListAll>>();
const defaultExpandKeys = ref([]);
const activeName = ref(1);

const queryFormRef = ref<ElFormInstance>();
const buildingTreeFormRef = ref<ElFormInstance>();
const buildingTreeTableRef = ref<ElTableInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: BuildingTreeForm = {
  id: undefined,
  parentId: undefined,
  type: undefined,
  name: undefined,
  orderNum: undefined,
  remark: undefined,
  status: undefined
};

const data = reactive<PageData<BuildingTreeForm, BuildingTreeQuery>>({
  form: { ...initFormData },
  queryParams: {
    parentId: undefined,
    type: undefined,
    name: undefined,
    orderNum: undefined,
    status: undefined,
    params: {}
  },
  rules: {}
});

const { queryParams, form, rules } = toRefs(data);

/** 查询宿舍楼管理列表 */
const getList = async () => {
  loading.value = true;
  const res = await listBuildingTree(queryParams.value);
  const data = proxy?.handleTree<BuildingTreeVO>(res.data, 'id', 'parentId');
  if (data) {
    buildingTreeList.value = data;
    defaultExpandKeys.value = [currentNodeData.value.id || data[0].id];
    loading.value = false;
  }
};

/** 查询宿舍楼管理下拉树结构 */
const getTreeselect = async () => {
  const res = await listBuildingTree();
  buildingTreeOptions.value = [];
  const data: BuildingTreeOption = { id: 0, name: '顶级节点', children: [] };
  data.children = proxy?.handleTree<BuildingTreeOption>(res.data, 'id', 'parentId');
  buildingTreeOptions.value.push(data);
};

// 取消按钮
const cancel = () => {
  reset();
  dialog.visible = false;
};

// 表单重置
const reset = () => {
  form.value = { ...initFormData };
  buildingTreeFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = (row?: BuildingTreeVO) => {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  dialog.visible = true;
  dialog.title = '添加宿舍楼管理';
};

/** 修改按钮操作 */
const handleUpdate = async (row: BuildingTreeVO) => {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.parentId;
  }
  const res = await getBuildingTree(row.id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改宿舍楼管理';
};

/** 提交按钮 */
const submitForm = () => {
  buildingTreeFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateBuildingTree(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addBuildingTree(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row: BuildingTreeVO) => {
  await proxy?.$modal.confirm('是否确认删除宿舍楼管理编号为"' + row.id + '"的数据项？');
  loading.value = true;
  await delBuildingTree(row.id).finally(() => (loading.value = false));
  currentNodeData.value.id = 1;
  getList();
  await getList();
  proxy?.$modal.msgSuccess('删除成功');
};

/** 通过条件过滤节点  */
const filterNode = (value: string, data: any) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

const listType = ref('T');
/** 节点单击事件 */
const handleNodeClick = (data: any) => {
  menuHide(data);
  currentNodeData.value = data;
  listType.value = data.type;
  // queryParams.value.name = data.name;
  // handleQuery();
  loadSsxx();
};

const loadSsxx = () => {
  const data = currentNodeData.value;
  switch (listType.value) {
    case 'T':
      buildingList.value.loadList();
      break;
    case 'B':
      floorList.value.loadList(data.sourceId);
      break;
    case 'F':
      roomList.value?.loadList(data.sourceId);
      break;
    case 'R':
      memberList.value?.loadList(data.sourceId);
      break;
  }
  memberListAll.value?.loadList(currentNodeData.value.type, currentNodeData.value.sourceId);
};

const addText = ref<string>('');
const currentNodeData = ref<any>({});
let addTextObj: any = {
  T: '宿舍楼',
  B: '楼层',
  F: '房间'
};
const openContextMenu = (event: any, nodeData: any) => {
  // 设置菜单的位置
  const menu = proxy?.$el.querySelector('.custom-menu');
  const clickX = event.clientX;
  const clickY = event.clientY;
  menu.style.left = clickX + 10 + 'px';
  menu.style.top = clickY + 'px';
  currentNodeData.value = nodeData;
  addText.value = addTextObj[nodeData.type];
  showMenu.value = true;
};

const menuItemAdd = (option: any) => {
  showMenu.value = false;
  switch (currentNodeData.value.type) {
    case 'T':
      buildingDialog.value?.handleAdd();
      break;
    case 'B':
      floorDialog.value?.handleAdd();
      break;
    case 'F':
      roomDialog.value?.handleAdd();
      break;
  }
};

const menuItemUpdate = (option: any) => {
  showMenu.value = false;
  switch (currentNodeData.value.type) {
    case 'B':
      buildingDialog.value?.handleUpdate(currentNodeData.value);
      break;
    case 'F':
      floorDialog.value?.handleUpdate(currentNodeData.value);
      break;
    case 'R':
      roomDialog.value?.handleUpdate(currentNodeData.value);
      break;
  }
};

const menuItemDelete = async () => {
  showMenu.value = false;
  switch (currentNodeData.value.type) {
    case 'B':
      buildingDialog.value?.handleDelete(currentNodeData.value);
      break;
    case 'F':
      floorDialog.value?.handleDelete(currentNodeData.value);
      break;
    case 'R':
      roomDialog.value?.handleDelete(currentNodeData.value);
      break;
  }
};

const menuHide = (option: any) => {
  showMenu.value = false;
};

const handleTabClick = (tab: any) => {
  activeName.value = tab.props.name;
  if (tab.props.name === 2) {
    memberListAll.value?.clearParams();
    memberListAll.value?.loadList(currentNodeData.value.type, currentNodeData.value.sourceId);
  }
};

const reloadDatas = () => {
  console.info('reloadDatas');
  getList();
  loadSsxx();
};

onMounted(() => {
  getList().then(() => {
    let rootData = buildingTreeList.value[0];
    handleNodeClick(rootData);
  });
});
</script>

<style lang="scss" scoped>
@import '@/assets/styles/variables.module.scss';
.custom-menu {
  position: fixed;
  background-color: #fff;
  border: 1px solid #ccc;
  border-radius: 4px;
  z-index: 1000;
}

.custom-menu ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.custom-menu ul li {
  padding: 8px 20px;
  cursor: pointer;
  font-size: 13px;
  color: $blue;
}

.custom-menu ul li:hover {
  background-color: #eee;
}
.ss-tabs {
  background-color: #fff;
}
</style>
